import { PropsWithChildren, useEffect } from 'react';
import {
  ChakraProvider,
  createLocalStorageManager,
  ToastProviderProps,
  extendTheme,
} from '@chakra-ui/react';
import { MantineProvider } from '@mantine/core';
import { Provider } from 'react-redux';
import { store } from './store/store';

import { addMiddleware, resetMiddlewares } from 'redux-dynamic-middlewares';
import { socketMiddleware } from 'services/events/middleware';
import { $authToken, $baseUrl, $socketBase } from 'services/api/client';

import './i18n';
const manager = createLocalStorageManager('@@d-color-mode');
const TOAST_OPTIONS: ToastProviderProps = {
  defaultOptions: { isClosable: true },
};
const colors = {
  brand: {
    50: '#fdefe8',
    100: '#e4d5cd',
    200: '#cfbbaf',
    300: '#bba091',
    400: '#a78672',
    500: '#8d6c58',
    600: '#6e5444',
    700: '#503c30',
    800: '#31241b',
    900: '#170a02',
  },
};

const theme = extendTheme({
  colors,
  styles: {
    global: () => ({
      '*': {
        '::-webkit-scrollbar': {
          display: 'none',
        },
        scrollbarWidth: 'none',
      },
    }),
  },
  fonts: {
    heading: 'Arial, sans-serif, "PingFang SC", "Microsoft YaHei"',
    body: 'Arial, sans-serif, "PingFang SC", "Microsoft YaHei"',
  },
  breakpoints: {
    sm: '320px',
    md: '768px',
    lg: '960px',
    xl: '1200px',
    '2xl': '1536px',
    '1080p': '1900px', // 1080p显示器
    '2k': '2550px', // 2k显示器
    '5xl': '3100px',
    '4k': '3800px', // 4k
  },
});

export default function UIProvider({ children }: PropsWithChildren) {
  const token = import.meta.env.VITE_APP_TOKEN;
  const apiUrl = import.meta.env.VITE_APP_API_PATH;
  const socketBase = import.meta.env.VITE_APP_SOCKET_BASE;

  useEffect(() => {
    // configure API client token
    if (token) {
      $authToken.set(token);
    }

    // configure API client base url
    if (apiUrl) {
      $baseUrl.set(apiUrl);
    }

    if (socketBase) {
      $socketBase.set(socketBase);
    }

    // reset dynamically added middlewares
    resetMiddlewares();

    // TODO: at this point, after resetting the middleware, we really ought to clean up the socket
    // stuff by calling `dispatch(socketReset())`. but we cannot dispatch from here as we are
    // outside the provider. it's not needed until there is the possibility that we will change
    // the `apiUrl`/`token` dynamically.

    // rebuild socket middleware with token and apiUrl
    addMiddleware(socketMiddleware());

    return () => {
      // Reset the API client token and base url on unmount
      $baseUrl.set(undefined);
      $authToken.set(undefined);
    };
  }, [apiUrl, token, socketBase]);

  return (
    <Provider store={store}>
      <MantineProvider>
        <ChakraProvider theme={theme} colorModeManager={manager} toastOptions={TOAST_OPTIONS}>
          {children}
        </ChakraProvider>
      </MantineProvider>
    </Provider>
  );
}
